import {AnyAction, Reducer} from 'redux';
import {EffectsCommandMap} from 'dva';
import {addAndUpdate, fetchDetail} from "./service";
import {message} from "antd";
import {IMenu} from "../data";
import router from "umi/router";

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelState {
  detail: IMenu;
  list: IMenu[];
}

export interface ModelType {
  namespace: string;
  state: ModelState;
  effects: {
    fetchDetail: Effect;
    addAndUpdate: Effect;
  };
  reducers: {
    saveDetail: Reducer<{}>;
    saveMenus: Reducer<{}>;
  };
}

const Model: ModelType = {
  namespace: 'menuSave',

  state: {
    detail: {},
    list: []
  },

  effects: {

    * fetchDetail({payload}, {call, put}) {
      // const response = yield call(fetchDetail, payload);

      const [response] = yield [
        call(fetchDetail, payload),
        // call(fetchMenus),
      ];

      // yield put({
      //   type: 'saveDetail',
      //   payload: response.data
      // })

      yield [
        put({
          type: 'saveDetail',
          payload: response.data
        }),
        // put({
        //   type: 'saveMenus',
        //   payload: menusResponse.list
        // })
      ];
    },
    * addAndUpdate({payload}, {call, put}) {
      const response = yield call(addAndUpdate, payload);
      if (response.status === 'ok') {
        message.success('操作成功');
        setTimeout(() => {
          router.push('/account/menu/list');
        }, 1000)
      } else {
        message.error(response.message);
      }
    },
  },

  reducers: {
    saveDetail(state, action) {
      return {
        ...state,
        detail: action.payload.detail||{},
        list: action.payload.menusTree
      };
    },
    saveMenus(state, action) {
      return {
        ...state,
        list: action.payload,
      };
    },
  },
};

export default Model;
